<template>
    <div class="flex-column hp100" ref="vm-statistics">
        <EnvironDesignModal v-show="!projectId"></EnvironDesignModal>
        <div class="flex-between" v-show="projectId">
            <EnvironDeploy
                showType="1"
                style="width: calc(100% - 300px)"
                v-if="projectId"
            ></EnvironDeploy>
            <div class="deploy-wrapper">
                <Progress
                    v-if="contentDetail.process > 0 && contentDetail.process < 100"
                    :percent="contentDetail.process"
                    status="active"
                    style="width: 100%"
                ></Progress>
                <div class="flex">
                    <!-- <Button type="primary" size="small" @click="gotoEdit" :disabled="!projectId" style="margin-right:7px">进入环境</Button> -->
                    <EnvironDeploy
                        showType="2"
                        v-if="projectId"
                        class="mr5"
                    ></EnvironDeploy>
                    <Tag color="primary"
                        style="flex:none"
                        ><Icon type="ios-stats" class="mr5" />{{
                            contentDetail.statusCHName
                        }}</Tag
                    >
                    <WarningTip
                        v-if="showDeployTip"
                    >
                      <span v-html="contentDetail.errorMessage || '失败原因请查看部署记录中的详情信息'"></span>
                    </WarningTip>
                    <Button
                        size="small"
                        type="text"
                        @click="deploy()"
                        v-if="projectId"
                        :disabled="!showDeployBtn"
                        >部署</Button
                    >
                    <Poptip
                        confirm
                        transfer
                        title="您确定要清空当前工程吗？"
                        @on-ok="clearDeploy"
                    >
                        <Button
                            size="small"
                            type="text"
                            v-if="projectId"
                            :disabled="!showClearDeployBtn"
                            >清空部署</Button
                        >
                    </Poptip>
                </div>
            </div>
        </div>
        <Card
            v-if="contentDetail.projectId"
            dis-hover
            :bordered="false"
            class="no-padding hp100 topo-card"
            style="flex:auto"
            :class="{ 'full-screen': fullShow.topo }"
        >
        <!-- 'full-screen-topo': fullShow.topo -->
            <template #title
                >拓扑</template
            >
            <template #extra>
                <div class="flex pointer extra" v-show="contentDetail.networkId">
                    <!-- <span @click="openCmdModal()" class="flex pointer icon-wrapper ml10"
                        ><span class="edit mr5"></span>执行命令</span
                    >
                    <span @click="openProtocolModal()" class="flex pointer icon-wrapper ml10"
                        ><span class="edit mr5"></span>数据通道</span
                    >
                    <span @click="openLinkCheckModal()" class="flex pointer icon-wrapper ml10"
                        ><span class="link mr5"></span>连通性校验</span
                    > -->
                    <span @click="refreshTopo" class="flex pointer icon-wrapper"
                        ><Icon :size="30" type="ios-refresh" style="position:relative;"/>刷新</span
                    >
                     <span @click="gotoEdit" class="flex pointer icon-wrapper ml10"
                        ><Icon :size="28" type="ios-create-outline" style="position:relative;"/>自定义编辑</span
                    >
                    <!-- <span
                        @click="fullScreen('topo')"
                        class="flex pointer icon-wrapper ml10"
                        ><span class="screen mr5"></span>{{fullShow.topo ? '取消全屏' : '全屏查看'}}</span
                    > -->
                </div>
            </template>
            <!-- /ky-topologyProject/index.html -->
            <Spin fix v-show="!load.topo" style="height: 100%">
                <Icon type="ios-loading" size="18" class="demo-spin-icon-load"></Icon>
                <div>加载中...</div>
            </Spin>
            <iframe
                ref="topoIframe"
                id="topoIframe" 
                :src="`/14-topologyProject/#/topoShowInTestReport?projectId=${contentDetail.projectId}`"
                width="100%"
                :height="fullShow.topo ? '100%' : '100%'"
                scrolling="none"
                frameborder="0"
                @load="loadSuccess('topo')"
                @error="loadSuccess('topo')"
            ></iframe>
            <!-- :src="`/ky-topologyProject/index.html#/topologyDisplay/preview?projectId=${
                    contentDetail.projectId
                }&ecId=${contentDetail.id}&ecName=${contentDetail.name}&type=${
                    fullShow.topo ? 'edit' : 'view'
                }`" -->
        </Card>
    </div>
</template>
<script>
    import { mapState } from 'vuex'
    import { getProjects } from '@/api/drill_compete'
    import EnvironDesignModal from '../environDesign.vue';
    import EnvironDeploy from '../environDeploy.vue';
    import {
        deployProject,
        queryProjectstatus,
        getDeployProgress,
        clearDeloyPro,
        getTestList,
        queryNetworkList,
    } from '../../api/deploy.js';
    export default {
        name:'EnvironManage',
        components:{ EnvironDesignModal, EnvironDeploy },
        inject:['detailParent'],
        props:{

        },
        data(){
            return {
                showDeployTip:false,
                query:{
                    pageIndex:1,
                    pageSize:10,
                    status:3
                },
                projectList:[],
                projectTotal:0,
                projectCol: [
                    {
                        type: 'link',
                        title: '名称',
                        key: 'name',
                        minWidth: 200,
                        tooltip: true,
                        // on:{
                        //     click:(row) => {
                        //         this.goTopo(row)
                        //     }
                        // }
                    },
                    {
                        title: '部署状态',
                        key: 'statusCHName',
                        minWidth: 110,
                        render: (h, params) => {
                            return h('div', [
                                h(
                                    'span',
                                    {
                                        style: {
                                            color: _this.$options.filters.deployStatusFilter(
                                                params.row,
                                                'color'
                                            )
                                        }
                                    },
                                    params.row.statusCHName
                                ),
                                h('WarningTip', {
                                    props:{
                                        error:true
                                    },
                                    style: {
                                        marginLeft: '4px',
                                        display:params.row.errorMessage
                                                ? 'inline-block'
                                                : 'none'
                                    }
                                },[
                                    h('span',{
                                        slot:"content",
                                        domProps:{
                                            innerHTML:params.row.errorMessage
                                        },
                                    })
                                ])
                            ]);
                        }
                    },
                    {
                        title:'虚拟机数量',
                        key:'vmCount',
                        tooltip: true,
                        minWidth: 60
                    },
                    {
                        title:"创建者",
                        key: 'creatorName',
                        tooltip: true,
                        minWidth: 100
                    },
                    {
                        title:"创建时间",
                        key: 'created',
                        tooltip: true,
                        minWidth: 135
                    } 
                ],
                fullShow: {
                    topo: false,
                    process: false,
                    code: false,
                },
                load: {
                    topo: false,
                    process: false,
                }
            }
        },
        computed: {
            ...mapState('user', ['userId', 'isRootDesigner']),
            contentDetail(){
                return this.detailParent.contentDetail
            },
            projectId(){
                return this.contentDetail.projectId
            },
            deployStatus() {
                return this.contentDetail.deployStatus;
            },
            showUnDeployBtn() {
                return [9, 13, 4].includes(this.deployStatus);
            },
            showDeployBtn() {
                return [0, -2, 3, 6, 14, 8].includes(this.deployStatus);
            },
            showClearDeployBtn() {
                return [3, 6, 14, 8].includes(this.deployStatus);
            },
        },
        mounted(){

        },
        methods:{
            getPrjList() {
                let params = {...this.query};
                if (this.isRootDesigner) {
                    params.enableAll = true;
                }
                getProjects(this.query).then((data) => {
                    if (data.code == 1) {
                        this.projectList = data.data.items;
                        this.projectTotal = data.data.total;
                    } else {
                        this.$Message.error(data.message);
                    }
                });
            },
            async deploy() {
            await this.deployProject(this.contentDetail.projectId);
            this.queryProjectstatus();
        },
        deployProject() {
            return new Promise((resolve, reject) => {
                deployProject(this.contentDetail.projectId).then(({ code, data, message }) => {
                    if (code === 1 || code === 3) {
                        resolve(code);
                    } else {
                        this.$Message.warning(message);
                    }
                });
            });
        },
        queryProjectstatus() {
                clearTimeout(this.statusTimeout);
                this.showDeployTip = false;
                if (!this.contentDetail.projectId) {
                    return;
                }
                return new Promise((resolve, reject) => {
                    queryProjectstatus(this.contentDetail.projectId).then(
                        ({ code, data, message }) => {
                            if (code === 1) {
                                let { project, network } = data;
                                let {
                                    id,
                                    deployId,
                                    status,
                                    statusCHName,
                                    checkOuts = [],
                                    errorMessage,
                                } = project;
                                this.getTestList(id); //获取场景列表
                                // this.getNetworkList(id, network.id); //获取子网络列表
                                this.detailParent.updateDetail({
                                    deployStatus: status,
                                    statusCHName: statusCHName,
                                    networkId: network.id,
                                    errorMessage:errorMessage
                                });
                                if (checkOuts.length != 0) {
                                    let errorContent = '';
                                    checkOuts.forEach((item,i) => {
                                        item.data.forEach((dataItem,dataIndex) => {
                                            dataItem.deviceName = dataItem.deviceName
                                                ? dataItem.deviceName
                                                : dataItem.networkName;
                                            errorContent +=
                                                dataItem.deviceName +
                                                '中的' +
                                                dataItem.name +
                                                item.message +
                                                '<br/>';
                                        });
                                    });
                                    // this.$Message.error({
                                    //     content: errorContent,
                                    //     closable: true,
                                    //     duration: 60
                                    // });
                                    this.showDeployTip = true;
                                } else if (errorMessage) {
                                    this.showDeployTip = true;
                                    // this.$Message.error({
                                    //     content: errorMessage,
                                    //     closable: true,
                                    //     duration: 30
                                    // });
                                } else {
                                    if (status === 9 || status === 13) {
                                        //部署中 || 清空部署中
                                        this.getDeployProgress(deployId);
                                    } else if (status === 15 || status === 16) {
                                        //校验中
                                        this.statusTimeout = setTimeout(() => {
                                            this.queryProjectstatus();
                                        }, 5000);
                                    } else if (status === 3) {
                                    }
                                }
                                resolve(project);
                            } else {
                                this.detailParent.updateDetail({ projectId: '' });
                                code != -2 && this.$Message.warning(message);
                            }
                        }
                    );
                });
            },
            getDeployProgress(deployId) {
                clearTimeout(this.progressTimeout);
                return new Promise((resolve, reject) => {
                    getDeployProgress(deployId).then(({ code, data, message }) => {
                        let { deployStatus, process } = data;
                        if (code === 1) {
                            this.detailParent.updateDetail({ process });
                            if (deployStatus === 1) {
                                // 还在部署中，持续获取部署进度
                                if (process != 100) {
                                    this.progressTimeout = setTimeout(() => {
                                        this.getDeployProgress(deployId);
                                    }, 5000);
                                }
                            } else {
                                // 部署完成
                                this.queryProjectstatus();
                            }
                            resolve(data);
                        } else {
                            this.$Message.warning(message);
                        }
                    });
                });
            },
            clearDeploy() {
                // this.loading = true;
                // this.distriTip = '正在清空工程';
                let params = {
                    projectId: this.contentDetail.projectId,
                };
                clearDeloyPro(this.contentDetail.projectId, params)
                    .then((res) => {
                        if (res.code === 1 || res.code === 3) {
                            this.queryProjectstatus();
                        } else {
                            // this.loading = false;
                            this.$Message.error({
                                content: res.message,
                                duration: 3,
                            });
                        }
                    })
                    .catch((err) => {
                        console.log(err);
                        // this.loading = false;
                        this.$Message.error('服务器连接失败！');
                    });
            },
            getTestList(projectId) {
                clearTimeout(this.sceneTimeout);
                getTestList(projectId).then(({ code, data, message }) => {
                    if (code === 1) {
                        if (data.items.length > 0) {
                            this.contentDetail.sceneId = data.items[0].id;
                        } else {
                            this.sceneTimeout = setTimeout(() => {
                                this.getTestList(projectId);
                            }, 3000);
                        }
                    }
                });
            },
            gotoTopo() {
                // window.openTrain(
                //     `http://localhost:8081/#/topologyDisplay/topologys?projectId=${this.projectId}&ecId=${this.contentId}&ecName=${this.contentDetail.name}`
                // );
                window.openTrain(
                    `/ky-topologyProject/index.html#/topologyDisplay/topologys?projectId=${this.projectId}&ecId=${this.contentId}&ecName=${this.contentDetail.name}`
                );
            },
            gotoEdit() {
                window.openTrain(
                    `/14-NetTopology/TopoEdit.html?project=${this.contentDetail.projectId}&networkid=${this.contentDetail.networkId}&hideReturnBtn=true`
                );
                // window.openTrain(
                //     `http://172.172.100.1/14-NetTopology/TopoEdit.html?project=${this.contentDetail.projectId}&networkid=${this.contentDetail.networkId}&fromProject=ky-topologyProject`
                // );
            },
            fullScreen(type) {
                if (type === 'topo') {
                    // 调用iframe中的方法
                    document.getElementById('topoIframe').contentWindow.changeShowType(this.fullShow[type] ? 'view' : 'edit');
                } else {
                    
                }
                this.fullShow[type] = !this.fullShow[type];
            },
            loadSuccess(type) {
                this.load[type] = true;
                if (type === 'code') {
                    //不同源无法js交互
                    // document.getElementById('codeIframe').contentWindow.document.getElementById('header').style.display = 'none';
                }
            },
            refreshTopo() {
                if (!this.load.topo) {
                    return;
                }
                this.load.topo = false;
                document.getElementById('topoIframe') &&
                document.getElementById('topoIframe').contentWindow.location.reload(true);
            },
        }
    }
</script>
<style scoped>
.deploy-record {
    height: 22px;
    width: 80px;
    margin-right: 10px;
}
.mr5 {
    margin-right: 5px;
}
.topo-card /deep/ .ivu-card-body {
    height: calc(100% - 20px);
}
.full-screen-topo /deep/ .ivu-card-head {
    display: none;
}
.full-screen-topo /deep/ .ivu-card-body {
    height: 100%;
}
.full-screen #topoIframe {
    height: 100%;
}
.icon-wrapper:hover {
    color: var(--url-color);
}
</style>